using System;
using System.Collections.Generic;
using Castle.MonoRail.Framework;
using Query;
using Rhino.Commons;
using WineCellar.Data;
using WineCellar.Web.Filters;

namespace WineCellar.Web.Controllers
{
    [Layout("index"), AuthenticationFilter,Rescue("generalerror")]    
    public class RegionController : ApplicationController
    {
        public void List()
        {
            if (IsAjaxRequest) { CancelLayout(); }
            ICollection<Region> regions = Repository<Region>.FindAll(OrderBy.Region.Name);
            PropertyBag["regions"] = regions;       
            RenderView("List");        
        }               
        public void New()
        {            
            PropertyBag["region"] = new Region();
        }
        public void Create([DataBind("region", Validate = true)]Region region)
        {
            if (!HasValidationError(region))
            {
                region.AddedBy = GetLoginUser();
                region.DateAdded = DateTime.Now;
            	Repository<Region>.Save(region);                
                PropertyBag["updatedObject"] = region;
            }
            else
            {
                Flash["updatedObject"] = region;
                Flash["summary"] = GetErrorSummary(region);                
            }
            RenderView("shared","create");
        }
        public void Edit(int id)
        {
            if (IsAjaxRequest) { CancelLayout(); }
        	Region region = Repository<Region>.Load(id);
            PropertyBag["region"] = region;                        
        }        
        public void View(int id)
        {
            if (IsAjaxRequest) { CancelLayout(); }
			PropertyBag["region"] = Repository<Region>.Load(id);         
        }
        public void Update([DataBind("region", Validate = true)] Region region)
        {
            if (!HasValidationError(region))
            {
            	With.Transaction(delegate
            	                 	{
										Repository<Region>.SaveOrUpdate(region);	
            	                 	});				
                PropertyBag["updatedObject"] = region;
            }
            else
            {
                Flash["updatedObject"] = region;
                Flash["summary"] = GetErrorSummary(region);                
            }   
            RenderView("shared","update");
        }         		
    }
}
